package cn.fanqinghong.org.service.impl;

import cn.fanqinghong.basic.service.impl.BaseServiceImpl;
import cn.fanqinghong.org.domain.Department;
import cn.fanqinghong.org.mapper.DepartmentMapper;
import cn.fanqinghong.org.service.IDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * FAN
 * 2022/6/1  11:54
 */
@Service
@Transactional(readOnly = true,propagation = Propagation.SUPPORTS)
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements IDepartmentService {
    @Autowired
    private DepartmentMapper departmentMapper;

    /**
     * 新增
     * @param department
     */
    @Override
    @Transactional
    public void save(Department department) {
        departmentMapper.save(department);//这里要返回自增ID，在xml中使用自增id的属性
        this.update(department);
    }

    /**
     * 修改
     * @param department
     */
    @Override
    @Transactional
    public void update(Department department) {
        StringBuilder dirPath = new StringBuilder();
        if (department.getParent() == null){
            //这里时顶级部门，拼接字符串为/+自己的id
            dirPath.append("/"+department.getId());
        }else{
            //这里是次级部门，拼接时，使用父级的dirPath+/+自己的id
            Department parent = departmentMapper.loadById(department.getParent().getId());//这里得到的时父级部门的dirPath
            dirPath.append(parent.getDirPath() + "/" + department.getId());
        }
        String s = dirPath.toString();
        department.setDirPath(s);
        departmentMapper.update(department);
    }

    /**
     * 无限级树
     * @return
     */
    @Override
    public List<Department> queryTree() {
        //查询全部的数据
        List<Department> departments = departmentMapper.loadAll();
        //把数据转换成Map的格式，key为id value为查宣导的所有值
        Map<Long, Department> allDepts = departments.stream().collect(Collectors.toMap(Department::getId, dept -> dept));
        //创建一个List数组用来存取第一级树
        List<Department> firstDepts = new ArrayList<>();
        //遍历循环departments 找到第一个级树
        for (Department tem : departments) {
            //如果遍历的数据中parent_id为null那么就是第一级树
            if (tem.getParent_id() == null){
                //把数据存储到第一级树
                firstDepts.add(tem);
            }else {
                //这里进入的是子级数，通过department找到夫级数的id，存入父级树的children中
                Department parent = allDepts.get(tem.getParent_id());
                if (parent != null){
                    parent.getChildren().add(tem);
                }
            }
        }
        //返回第一级树
        return firstDepts;
    }

}
